package com.crazy.practice.boot.controller;

import com.crazy.practice.boot.core.UpdatePropertiesUtil;
import com.crazy.practice.boot.even.PropertiesChangeHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author panyonghui
 * @describe 文件更新控制器
 * @date 2023/3/2 16:11
 */
@RequestMapping("/file")
@RestController
public class FileController {

    /**
     * 监听器事件发布器
     */
    @Autowired
    private PropertiesChangeHandle propertiesChangeHandle;

    /**
     * 更新配置项信息
     * @param key
     * @param value
     * @param comments
     * @return java.lang.String
     */
    @GetMapping("/updateProperties")
    public String updateProperties(@RequestParam(value = "key")String key, @RequestParam(value = "value")String value, @RequestParam(value = "comments", required = false)String comments){
        Map map = new HashMap();
        map.put(key, value);
        Properties properties = new Properties();
        properties.put(key, value);
        propertiesChangeHandle.changeProperties(properties);
        return value;
    }

    @GetMapping("/readProperties")
    public Map readProperties(){
        Map proMap = new HashMap();
        Properties properties = UpdatePropertiesUtil.readProperties();
        Enumeration enumeration = properties.propertyNames();
        while (enumeration.hasMoreElements()){
            String key = (String) enumeration.nextElement();
            proMap.put(key, properties.getProperty(key));
        }
        return proMap;
    }
}
